/** 启动页 */
import React, {
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import {Animated, Image, StyleSheet, Text, View} from 'react-native';
import {AppConfig, getJson} from './services';
import {getItem, setItem} from './utils';
import {
  APP_CONFIG,
  CARTOON_DATA,
  NOVEL_DATA,
  USER_INFO,
  VIDEO_DATA,
} from './constants';
import {useGlobalStore, useHomeStore, useUserInfoStore} from './mobx';
import Layout from './Layout';
// import cfJson from './mock/appconfig.json';

const defaultPoster = 'https://img-home.csdnimg.cn/images/20240218021830.png';

function SplashScreen({children}: {children: ReactNode}) {
  const [url, setUrl] = useState();
  const {setCurData} = useHomeStore();
  const {changeAppConfig} = useGlobalStore();
  const {setUserInfo} = useUserInfoStore();
  const [isApp, setIsApp] = useState(false);
  const countRef = useRef(0);
  const aniRef = useRef(new Animated.Value(0)).current;

  const initHome = async (config?: any) => {
    setUrl(config?.PopAdList?.[0]?.ImgUrl || defaultPoster);
    if (config?.WebSiteFileDoMain) {
      const jsonD = await getJson(
        `${config?.WebSiteFileDoMain}${config?.MHJsonAddress}`,
      );
      setCurData(jsonD as any);
      setItem(CARTOON_DATA, jsonD);
      getJson(`${config?.WebSiteFileDoMain}${config?.XSJsonAddress}`)
        .then(res => {
          setItem(NOVEL_DATA, res);
        })
        .catch(() => {});
      getJson(`${config?.WebSiteFileDoMain}${config?.SPJsonAddress}`)
        .then(res => {
          setItem(VIDEO_DATA, res);
        })
        .catch(() => {});
    }
  };

  const getAppData = useCallback(async () => {
    const config = await getItem(APP_CONFIG);
    const info = await getItem(USER_INFO);
    if (info && info.Token) {
      setUserInfo(info);
    }
    if (config && config?.WebSiteFileDoMain) {
      changeAppConfig(config);
      await initHome(config);
    } else {
      AppConfig()
        .then(async (res: any) => {
          if (res && res.Data) {
            changeAppConfig(res.Data);
            await setItem(APP_CONFIG, res?.Data);
            await initHome(res?.Data);
          } else {
            throw Error('配置获取失败');
          }
        })
        .catch(err => {
          //   changeAppConfig(cfJson.Data as any);
          countRef.current++;
          if (countRef.current < 4) {
            getAppData();
          } else {
            console.error(err);
          }
        });
    }
  }, [setUserInfo, changeAppConfig]);

  useEffect(() => {
    getAppData();
  }, [getAppData]);

  useEffect(() => {
    if (url) {
      Animated.timing(aniRef, {
        toValue: 1,
        duration: 3000,
        useNativeDriver: true,
      }).start(() => {
        setTimeout(() => {
          setIsApp(true);
        }, 1000);
      });
    }
  }, [url]);

  if (isApp) {
    return <Layout>{children}</Layout>;
  }

  return (
    <View style={{flex: 1}}>
      {url ? (
        <Animated.Image
          source={{uri: url}}
          style={{...styles.image, opacity: aniRef}}
        />
      ) : (
        <Image source={{uri: defaultPoster}} style={styles.image} />
      )}
    </View>
  );
}

export default SplashScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    width: '100%',
    height: '100%',
    resizeMode: 'contain',
  },
});
